package club.hicode.daydayup.monitor;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


import cn.hutool.core.util.StrUtil;
import com.sun.management.OperatingSystemMXBean;

public class WinProcessCollector implements ICollector{
    private static final int CPUTIME = 5000;
    private static final int PERCENT = 100;
    private static final int FAULTLENGTH = 10;
  
    public MonitorInfoBean getMonitorInfoBean(MonitorInfoBean infoBean) throws Exception {  
        int kb = 1024;  
        long totalMemory = Runtime.getRuntime().totalMemory() / kb;  
        long freeMemory = Runtime.getRuntime().freeMemory() / kb;  
        long maxMemory = Runtime.getRuntime().maxMemory() / kb;  
        OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory  
                .getOperatingSystemMXBean();  
        String osName = System.getProperty("os.name");  
        HashMap<String, Long> mems = getSystemMem(); 
        int avaliableprocs = osmxb.getAvailableProcessors();
        String hostName = getSystemHostName();
        ThreadGroup parentThread;  
        for (parentThread = Thread.currentThread().getThreadGroup(); parentThread  
                .getParent() != null; parentThread = parentThread.getParent());  
        int totalThread = parentThread.activeCount();  
        double cpuRatio = 0;  
        if (osName.toLowerCase().startsWith("windows")) {  
            cpuRatio = this.getCpuRatio(null);  
        }  
        if(cpuRatio < 0) Math.abs(cpuRatio);
        if(null == infoBean) infoBean = new MonitorInfoBean();  
        infoBean.osName = osName;  
        infoBean.freeMemory = freeMemory;  
        infoBean.maxMemory = maxMemory; 
        infoBean.totalMemory = totalMemory;
        infoBean.installPhysicalMemorySize = getTotalPhysicMem();
        infoBean.totalPhysicalMemorySize = mems.get("TotalVisibleMemorySize");
        infoBean.freePhysicalMemorySize =  mems.get("FreePhysicalMemory");
        infoBean.totalVirtualMemorySize = mems.get("TotalVirtualMemorySize");
        infoBean.freeVirtualMemory = mems.get("FreeVirtualMemory");
        infoBean.totalSwapSpaceSize = mems.get("TotalSwapSpaceSize");
        infoBean.freeSpaceInPagingFiles = mems.get("FreeSpaceInPagingFiles");
        infoBean.SizeStoredInPagingFiles = mems.get("SizeStoredInPagingFiles");
        infoBean.totalThread = totalThread;  
        infoBean.cpuRatio = cpuRatio; 
        infoBean.avliaProcessCount = avaliableprocs;
        infoBean.hostName = hostName;
        infoBean.logicDiskInfos = readSystemLogicDiskInfo(infoBean);
        return infoBean;  
    }  
  
    public double getCpuRatio(String processName) {  
        try {  
        	//where Caption=\"System Idle Process,"+processName+"\"
            String procCmd = System.getenv("windir")  
                    + "\\system32\\wbem\\wmic.exe process get Caption,CommandLine,"  
                    + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";  
            long[] c0 = readCpu(Runtime.getRuntime().exec(procCmd), processName);  
            try{
            	Thread.sleep(CPUTIME); 
            }catch(Exception e){}
            long[] c1 = readCpu(Runtime.getRuntime().exec(procCmd), processName);  
            if (c0 != null && c1 != null) {  
                long idletime = c1[0] - c0[0];  
                long busytime = c1[1] - c0[1];  
                return Double.valueOf(  
                        PERCENT * (busytime) / (busytime + idletime))  
                        .doubleValue();  
            } else {  
                return 0.0;  
            }  
        } catch (Exception ex) {  
            ex.printStackTrace();  
            return 0.0;  
        }  
    }  
    
    public long[] readCpu(final Process proc, String ProcessName) {  
        long[] retn = new long[2];  
        try {  
            proc.getOutputStream().close();  
            InputStreamReader ir = new InputStreamReader(proc.getInputStream());  
            LineNumberReader input = new LineNumberReader(ir);  
            String line = input.readLine();  
            if (line == null || line.length() < FAULTLENGTH) {  
                return null;  
            }  
            int capidx = line.indexOf("Caption");  
            int cmdidx = line.indexOf("CommandLine");  
            int rocidx = line.indexOf("ReadOperationCount");  
            int umtidx = line.indexOf("UserModeTime");  
            int kmtidx = line.indexOf("KernelModeTime");  
            int wocidx = line.indexOf("WriteOperationCount");  
            long idletime = 0;  
            long kneltime = 0;  
            long usertime = 0;  
            while ((line = input.readLine()) != null) {  
                if (line.length() < wocidx) {  
                    continue;  
                }  
                String caption = Bytes.substring(line, capidx, cmdidx - 1).trim();  
                String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();  
                if (cmd.indexOf("wmic.exe") >= 0) {  
                    continue;  
                } 
                if (caption.equals("System Idle Process")  
                        || caption.equals("System")) {
                    idletime += Long.valueOf(  
                            Bytes.substring(line, kmtidx, rocidx - 1).trim())  
                            .longValue();  
                    idletime += Long.valueOf(  
                            Bytes.substring(line, umtidx, wocidx - 1).trim())  
                            .longValue();  
                    continue;  
                } 
                if(null != ProcessName && !ProcessName.equals(caption)) continue;
                kneltime += Long.valueOf(  
                        Bytes.substring(line, kmtidx, rocidx - 1).trim())  
                        .longValue();  
                usertime += Long.valueOf(  
                        Bytes.substring(line, umtidx, wocidx - 1).trim())  
                        .longValue();  
            }  
            retn[0] = idletime;  
            retn[1] = kneltime + usertime;  
            return retn;  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        } finally {  
            try {  
                proc.getInputStream().close();  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
        return null;  
    }  
      
    public void getProcessInfo(String ProcessName, String pid) {  
        try {  
            String procCmd = System.getenv("windir")  
                    + "\\system32\\wbem\\wmic.exe process ";
                    if(!StrUtil.isNotBlank(ProcessName) || !StrUtil.isNotBlank(pid)){
                    	procCmd = procCmd+"where ";
                    	boolean hasc = false;
                    	if(!StrUtil.isNotBlank(ProcessName)){
                    		hasc = true;
                    		procCmd = procCmd+ "\"Name='"+ProcessName+"'";
                    	}
                    		
                    	if(!StrUtil.isNotBlank(pid)){
                    		if(hasc) procCmd = procCmd+ " and ";
                    		else procCmd = procCmd+ "\" ";
                    		procCmd = procCmd + "ProcessId='"+pid+"'";
                    	}
                    	procCmd = procCmd +"\"";
                    }
                    procCmd = procCmd + " get Caption,CommandLine,"  
                    + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";  
            Process pcs = Runtime.getRuntime().exec(procCmd);
            BufferedReader br = new BufferedReader(new InputStreamReader(pcs.getInputStream()));
            String line = null;
            while((line = br.readLine()) !=null ){
            	if(!StrUtil.isNotBlank(line))System.out.println("line="+line);
            }
        } catch (Exception ex) {  
            ex.printStackTrace();  
        }  
    }
    
    public static long readCpu_idletime() {  
        long idletime = 1;
        Process proc = null;
        try {
        	 String procCmd = System.getenv("windir")  
             + "\\system32\\wbem\\wmic.exe process where \"Name='System Idle Process'\" get Caption,CommandLine,"  
             + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";  
        	proc = Runtime.getRuntime().exec(procCmd);
        	proc.getOutputStream().close();  
            InputStreamReader ir = new InputStreamReader(proc.getInputStream());  
            LineNumberReader input = new LineNumberReader(ir);  
            String line = input.readLine();  
            if (line == null || line.length() < FAULTLENGTH) {  
                return idletime;
            }  
            int capidx = line.indexOf("Caption");  
            int cmdidx = line.indexOf("CommandLine");  
            int rocidx = line.indexOf("ReadOperationCount");  
            int umtidx = line.indexOf("UserModeTime");  
            int kmtidx = line.indexOf("KernelModeTime");  
            int wocidx = line.indexOf("WriteOperationCount");  
            while ((line = input.readLine()) != null) { 
                if (line.length() < wocidx) {  
                    continue;  
                }  
                String caption = Bytes.substring(line, capidx, cmdidx - 1)  
                        .trim();  
                String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();  
                if (cmd.indexOf("wmic.exe") >= 0) {  
                    continue;
                } 
                if (caption.equals("System Idle Process")  
                        || caption.equals("System")) {
                    idletime += Long.valueOf(  
                            Bytes.substring(line, kmtidx, rocidx - 1).trim())  
                            .longValue();  
                    idletime += Long.valueOf(  
                            Bytes.substring(line, umtidx, wocidx - 1).trim())  
                            .longValue();  
                    continue;  
                } 
            }  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        } finally {  
            try {  
                proc.getInputStream().close();  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
        return idletime;  
    }
    
    public static long readePIDCpu_busyTime(String pid) {
        Process proc = null;
        long busyTime = 0;
        try {
        	 String procCmd = System.getenv("windir")  
             + "\\system32\\wbem\\wmic.exe process where \"ProcessId='"+pid+"'\" get Caption,CommandLine,"  
             + "KernelModeTime,ReadOperationCount,ThreadCount,UserModeTime,WriteOperationCount";  
        	proc = Runtime.getRuntime().exec(procCmd);
            proc.getOutputStream().close();
            InputStreamReader ir = new InputStreamReader(proc.getInputStream());  
            LineNumberReader input = new LineNumberReader(ir);  
            String line = input.readLine();
            if (line == null || line.length() < FAULTLENGTH) {  
                return busyTime;
            }  
            int cmdidx = line.indexOf("CommandLine");  
            int rocidx = line.indexOf("ReadOperationCount");  
            int umtidx = line.indexOf("UserModeTime");  
            int kmtidx = line.indexOf("KernelModeTime");  
            int wocidx = line.indexOf("WriteOperationCount");  
            long kneltime = 0;  
            long usertime = 0;
            while ((line = input.readLine()) != null) {  
                if (line.length() < wocidx) {  
                    continue;
                }  
                String cmd = Bytes.substring(line, cmdidx, kmtidx - 1).trim();
                if (cmd.indexOf("wmic.exe") >= 0) {
                    continue;  
                } 
                kneltime = Long.valueOf(  
                        Bytes.substring(line, kmtidx, rocidx - 1).trim())  
                        .longValue();  
                usertime = Long.valueOf(  
                        Bytes.substring(line, umtidx, wocidx - 1).trim())  
                        .longValue();
                
                busyTime = kneltime + usertime;
            }  
        } catch (Exception ex) {  
            ex.printStackTrace();  
        } finally {  
            try {  
                proc.getInputStream().close();  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
        }  
        return busyTime;  
    }
    
    public static ProcessInfo readProcessNamePidsInfo(String processName , String pid) {
    	ProcessInfo pidInfo = null;
        Process proc = null;
        try {
        	 String procCmd = System.getenv("windir")  
             + "\\system32\\wbem\\wmic.exe process where \"Name='"+processName+"'\" get Caption,ParentProcessId,ProcessId,WorkingSetSize,VirtualSize";  
        	proc = Runtime.getRuntime().exec(procCmd);
            proc.getOutputStream().close();  
            InputStreamReader ir = new InputStreamReader(proc.getInputStream());  
            LineNumberReader input = new LineNumberReader(ir);  
            String line = input.readLine();
            if (line == null || line.length() < FAULTLENGTH) {  
                return null;
            }  
//            int pid_idx = line.indexOf("ProcessId");
//            int ppid_idx = line.indexOf("ParentProcessId");
//            int wss_idx = line.indexOf("WorkingSetSize");
//            int vss_idx = line.indexOf("VirtualSize");
            ArrayList<Long> busytimes = new ArrayList<Long>();
            ArrayList<Long> idletimes = new ArrayList<Long>();
            pidInfo = new ProcessInfo() ;
            while ((line = input.readLine()) != null) {
            	if(StrUtil.isNotBlank(line)) continue;
            	String[] arr = line.trim().replaceAll("\\s+{0,}", " ").split(" ") ;
            	if(arr!=null && arr.length >= 5){
            		pidInfo.ProcessName = arr[0];
                	pidInfo.PProcessId = Long.valueOf(arr[1].trim());
                	pidInfo.ProcessId = Long.valueOf(arr[2].trim());
                	pidInfo.memoryInuse = Double.valueOf(ProcessResourceCollector.FORMAT.format(Double.valueOf(arr[3].trim()) / (1024 * 1024)));
                	pidInfo.VirtualSize = Double.valueOf(ProcessResourceCollector.FORMAT.format(Double.valueOf(arr[4]) / (1024 * 1024)));
                    idletimes.add(readCpu_idletime());
                    busytimes.add(readePIDCpu_busyTime(""+pidInfo.ProcessId));
            	}
            }
            if(null != pidInfo ){
            	Thread.sleep(CPUTIME);
        		long idletime = readCpu_idletime() - idletimes.get(0);
        		long busytime = readePIDCpu_busyTime(""+pidInfo.ProcessId) - busytimes.get(0);
        		pidInfo.cpuUsage = Double.valueOf(
        				PERCENT * (busytime) / (busytime + idletime)
        			) .doubleValue();
        		pidInfo.cpuUsage = Math.abs(pidInfo.cpuUsage);
            }
        } catch (Exception ex) {  
            ex.printStackTrace(); 
        } finally {  
            try {  
                proc.getInputStream().close();
            } catch (Exception e) {  
                e.printStackTrace();
            }
        }  
        return pidInfo;  
    }
    
    public static List<LogicDiskInfo> readSystemLogicDiskInfo(MonitorInfoBean infoBean) {
    	Process proc = null;
    	MonitorInfoBean infoBeano = infoBean;
    	List<LogicDiskInfo> logicDiskInfos = null;
    	if(null != infoBeano){
    		infoBean.avliaLogicDiskCount = 0;
    		logicDiskInfos = infoBean.logicDiskInfos;
    	}
    	if(null == logicDiskInfos) {
    		logicDiskInfos = new ArrayList<LogicDiskInfo>();
    	}
    	
        try {
        	 String procCmd = System.getenv("windir")  
             + "\\system32\\wbem\\wmic.exe logicaldisk get Caption, Description, DeviceID, DriveType, FileSystem, FreeSpace, Size, VolumeName";  
        	proc = Runtime.getRuntime().exec(procCmd);
            proc.getOutputStream().close();  
            InputStreamReader ir = new InputStreamReader(proc.getInputStream());  
            LineNumberReader input = new LineNumberReader(ir);  
            String line = input.readLine();
            if (line == null || line.length() < FAULTLENGTH) {  
                return null;
            }
            int cap_idx = line.indexOf("Caption");
            int desc_idx = line.indexOf("Description");
            int did_idx = line.indexOf("DeviceID");
            int drt_idx = line.indexOf("DriveType");
            int fsys_idx = line.indexOf("FileSystem");
            int fsp_idx = line.indexOf("FreeSpace");
            int size_idx = line.indexOf("Size");
            int voln_idx = line.indexOf("VolumeName");
            int logicdiskindx = 0;
            int createdLen = logicDiskInfos.size();
            LogicDiskInfo diskoinfo = null;
            long diskTotalSize = 0;
            long diskTotalFreeSize = 0;
            while ((line = input.readLine()) != null) {
            	if(StrUtil.isNotBlank(line)) continue;
            	if(createdLen > logicdiskindx){
            		diskoinfo = logicDiskInfos.get(logicdiskindx);
            	}else{
            		diskoinfo = new LogicDiskInfo();
            		logicDiskInfos.add(diskoinfo);
            	}
            	logicdiskindx ++;
            	diskoinfo.Caption = Bytes.substring(line, cap_idx, desc_idx - 1) .trim();
            	diskoinfo.Description = Bytes.substring(line, desc_idx, did_idx - 1) .trim();
            	diskoinfo.DeviceID = Bytes.substring(line, did_idx, drt_idx - 1) .trim();
            	diskoinfo.DriveType = Bytes.substring(line, drt_idx, fsys_idx - 1) .trim();
            	diskoinfo.FileSystem = Bytes.substring(line, fsys_idx, fsp_idx - 1) .trim();
            	String freeSpace = Bytes.substring(line, fsp_idx, size_idx - 1) .trim();
            	if(!StrUtil.isNotBlank(freeSpace)){
            		diskoinfo.FreeSpace = Double.valueOf(freeSpace) /1024/1024;
            		diskTotalFreeSize += diskoinfo.FreeSpace;
            	}else{
            		diskoinfo.FreeSpace = -1;
            	}
            	String size = Bytes.substring(line, size_idx, voln_idx - 1) .trim();
            	if(!StrUtil.isNotBlank(size)){
            		diskoinfo.Size = Double.valueOf(size) /1024/1024;
            		diskTotalSize += diskoinfo.Size;
            	}else{
            		diskoinfo.Size = -1;
            	}
            	diskoinfo.VolumeName = Bytes.substring(line, voln_idx, (line.getBytes().length - 1) ) .trim();
           	}
            if(null != infoBeano){
        		infoBean.avliaLogicDiskCount = logicdiskindx;
        		infoBean.diskTotalSize = diskTotalSize;
        		infoBean.diskTotalFreeSize = diskTotalFreeSize;
        	}
        } catch (Exception ex) {  
            ex.printStackTrace(); 
        } finally {  
            try {  
                proc.getInputStream().close();
            } catch (Exception e) {  
                e.printStackTrace();
            }
        }  
        return logicDiskInfos;  
    }
    
    public static String getSystemHostName() {
    	Process proc = null;
    	String hostName = null;
        try {
        	 String procCmd = System.getenv("windir")  
             + "\\system32\\wbem\\wmic.exe computersystem get Name";  
        	proc = Runtime.getRuntime().exec(procCmd);
            proc.getOutputStream().close();  
            InputStreamReader ir = new InputStreamReader(proc.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String line = input.readLine();
            //System.out.println(line);
            if (line == null || line.length() < FAULTLENGTH) {
                return null;
            }
            int name_idx = line.indexOf("Name");
            while ((line = input.readLine()) != null) {
            	if(StrUtil.isNotBlank(line)) continue;
            	hostName = Bytes.substring(line, name_idx, (line.getBytes().length -1) ) .trim();
           	}
        } catch (Exception ex) {  
            ex.printStackTrace(); 
        } finally {  
            try {  
                proc.getInputStream().close();
            } catch (Exception e) {  
                e.printStackTrace();
            }
        }  
        return hostName;  
    }
    
    public static HashMap<String, Long> getSystemMem(){
    	Process proc = null;
    	HashMap<String, Long> meminfos = new HashMap<String, Long>();
    	meminfos.put("FreePhysicalMemory", 0L);
    	meminfos.put("FreeSpaceInPagingFiles", 0L);
    	meminfos.put("FreeVirtualMemory", 0L);
    	meminfos.put("MaxProcessMemorySize", 0L);
    	meminfos.put("SizeStoredInPagingFiles", 0L);
    	meminfos.put("TotalSwapSpaceSize", 0L);
    	meminfos.put("TotalVirtualMemorySize", 0L);
    	meminfos.put("TotalVisibleMemorySize", 0L);
        try {
        	 String procCmd = System.getenv("windir")  
        	 +"\\system32\\wbem\\wmic.exe OS get FreePhysicalMemory,FreeSpaceInPagingFiles,FreeVirtualMemory,MaxProcessMemorySize,SizeStoredInPagingFiles,TotalSwapSpaceSize,TotalVirtualMemorySize,TotalVisibleMemorySize";
        	proc = Runtime.getRuntime().exec(procCmd);
            proc.getOutputStream().close();  
            InputStreamReader ir = new InputStreamReader(proc.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String line = input.readLine();
            if (line == null || line.length() < FAULTLENGTH) {
                return null;
            }
            int frephy_idx = line.indexOf("FreePhysicalMemory");
            int freespainp_idx = line.indexOf("FreeSpaceInPagingFiles");
            int freevir_idx = line.indexOf("FreeVirtualMemory");
            int maxproc_idx = line.indexOf("MaxProcessMemorySize");
            int sstoreinp_idx = line.indexOf("SizeStoredInPagingFiles");
            int totalswp_idx = line.indexOf("TotalSwapSpaceSize");
            int totalvir_idx = line.indexOf("TotalVirtualMemorySize");
            int totalvisi_idx = line.indexOf("TotalVisibleMemorySize");
            while((line = input.readLine()) != null) {
            	if(StrUtil.isNotBlank(line)) continue;
            	
            	String FreePhysicalMemory = Bytes.substring(line, frephy_idx, freespainp_idx - 1) .trim();
            	if(!StrUtil.isNotBlank(FreePhysicalMemory)){
            		meminfos.put("FreePhysicalMemory",  Long.valueOf(FreePhysicalMemory));
            	}else{
            		meminfos.put("FreePhysicalMemory", 0L);
            	}
            	String FreeSpaceInPagingFiles = Bytes.substring(line, freespainp_idx, freevir_idx - 1) .trim();
            	if(!StrUtil.isNotBlank(FreeSpaceInPagingFiles)){
            		meminfos.put("FreeSpaceInPagingFiles",  Long.valueOf(FreeSpaceInPagingFiles));
            	}else{
            		meminfos.put("FreeSpaceInPagingFiles", 0L);
            	}
            	String FreeVirtualMemory = Bytes.substring(line, freevir_idx, maxproc_idx - 1) .trim();
            	if(!StrUtil.isNotBlank(FreeVirtualMemory)){
            		meminfos.put("FreeVirtualMemory",  Long.valueOf(FreeVirtualMemory));
            	}else{
            		meminfos.put("FreeVirtualMemory", 0L);
            	}
            	String MaxProcessMemorySize = Bytes.substring(line, maxproc_idx, sstoreinp_idx - 1) .trim();
            	if(!StrUtil.isNotBlank(MaxProcessMemorySize)){
            		meminfos.put("MaxProcessMemorySize",  Long.valueOf(MaxProcessMemorySize));
            	}else{
            		meminfos.put("MaxProcessMemorySize", 0L);
            	}
            	String SizeStoredInPagingFiles = Bytes.substring(line, sstoreinp_idx, totalswp_idx - 1) .trim();
            	if(!StrUtil.isNotBlank(SizeStoredInPagingFiles)){
            		meminfos.put("SizeStoredInPagingFiles",  Long.valueOf(SizeStoredInPagingFiles));
            	}else{
            		meminfos.put("SizeStoredInPagingFiles", 0L);
            	}
            	String TotalSwapSpaceSize = Bytes.substring(line, totalswp_idx, totalvir_idx - 1) .trim();
            	if(!StrUtil.isNotBlank(TotalSwapSpaceSize)){
            		meminfos.put("TotalSwapSpaceSize",  Long.valueOf(TotalSwapSpaceSize));
            	}else{
            		meminfos.put("TotalSwapSpaceSize", 0L);
            	}
            	String TotalVirtualMemorySize = Bytes.substring(line, totalvir_idx, totalvisi_idx - 1) .trim();
            	if(!StrUtil.isNotBlank(TotalVirtualMemorySize)){
            		meminfos.put("TotalVirtualMemorySize",  Long.valueOf(TotalVirtualMemorySize));
            	}else{
            		meminfos.put("TotalVirtualMemorySize", 0L);
            	}
            	String TotalVisibleMemorySize = Bytes.substring(line, totalvisi_idx, (line.getBytes().length - 1) ) .trim();
            	if(!StrUtil.isNotBlank(TotalVisibleMemorySize)){
            		meminfos.put("TotalVisibleMemorySize",  Long.valueOf(TotalVisibleMemorySize));
            	}else{
            		meminfos.put("TotalVisibleMemorySize", 0L);
            	}
           	}
        } catch (Exception ex) {  
            ex.printStackTrace(); 
        } finally {  
            try {  
                proc.getInputStream().close();
            } catch (Exception e) {  
                e.printStackTrace();
            }
        }  
        return meminfos; 
    }
    
    public static long getTotalPhysicMem(){
    	Process proc = null;
    	long totalPhysicMem = 0L;
        try {
        	/*
        	wmic LOGICALDISK get Caption,Description,DeviceID,DriveType,FileSystem,FreeSpace,Size,VolumeName
        	 */
        	 String procCmd = System.getenv("windir")  
             + "\\system32\\wbem\\wmic.exe memorychip get Capacity";
        	proc = Runtime.getRuntime().exec(procCmd);
            proc.getOutputStream().close();  
            InputStreamReader ir = new InputStreamReader(proc.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            String line = input.readLine();
            if (line == null || line.length() < FAULTLENGTH) {
                return 0L;
            }
            int cap_idx = line.indexOf("Capacity");
            while ((line = input.readLine()) != null) {
            	if(StrUtil.isNotBlank(line)) continue;
            	totalPhysicMem = Long.valueOf(Bytes.substring(line, cap_idx, (line.getBytes().length -1) ) .trim()) / 1024;
           	}
        } catch (Exception ex) {  
            ex.printStackTrace(); 
        } finally {  
            try {  
                proc.getInputStream().close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }  
        return totalPhysicMem; 
    }
    
    public static void main(String[] args) throws Exception { 
//    	WinProcessCollector d = new WinProcessCollector(); 
//        MonitorInfoBean monitorInfo = d.getMonitorInfoBean(null); 
//        System.out.println("主机名=" + monitorInfo.hostName);
//        System.out.println("主机名IP=" + monitorInfo.IP); 
//        System.out.println("主机名系统名=" + monitorInfo.osName); 
//        System.out.println("cpu占有率=" + monitorInfo.cpuRatio);  
//          
//        System.out.println("可使用核心内存=" + monitorInfo.totalMemory);  
//        System.out.println("剩余核心内存=" + monitorInfo.freeMemory);  
//        System.out.println("最大可使用核心内存=" + monitorInfo.maxMemory);  
//          
//        System.out.println("操作系统=" + monitorInfo.osName);  
//        System.out.println("总的物理内存=" + monitorInfo.totalPhysicalMemorySize + "kb");  
//        System.out.println("剩余的物理内存=" + monitorInfo.freePhysicalMemorySize + "kb");  
//        
//        System.out.println("总虚拟内存=" + monitorInfo.totalVirtualMemorySize + "kb");  
//        System.out.println("可用虚拟内存=" + monitorInfo.freeVirtualMemory + "kb");  
//        
//        System.out.println("内存交换区大小=" + monitorInfo.totalSwapSpaceSize + "kb");  
//        
//        System.out.println("内存总计=" + monitorInfo.SizeStoredInPagingFiles + "kb");
//        System.out.println("可分配内存总计=" + monitorInfo.freeSpaceInPagingFiles + "kb"); 
//        System.out.println("java线程总数=" + monitorInfo.totalThread + "kb");
    	
    	/*d.getProcessInfo("plsqldev.exe", null);
    	
    	List<ProcessInfo> appprocesss = readProcessNamePidsInfo("plsqldev.exe", null);
    	 for(ProcessInfo prcess : appprocesss){
    		 System.out.println(prcess.ProcessName+","+prcess.ProcessId+","+prcess.PProcessId+","
    				 +prcess.cpuUsage+","+prcess.memoryInuse/1024+","+prcess.VirtualSize/1024);
    	 }*/
    	
    	/*MonitorInfoBean infoBean = new MonitorInfoBean();
    	List<LogicDiskInfo> logicDiskInfos = new ArrayList<LogicDiskInfo>();
    	infoBean.logicDiskInfos = logicDiskInfos;
    	for(int i =0 ; i < 10; i++) logicDiskInfos.add(new LogicDiskInfo());
    	infoBean.avliaLogicDiskCount = 0;
    	
    	logicDiskInfos = readSystemLogicDiskInfo(infoBean);
    	System.out.println("infoBean.getAvliaLogicDiskCount():"+infoBean.avliaLogicDiskCount);
    	System.out.println("logicDiskInfos.size():"+logicDiskInfos.size());
    	
    	System.out.println("DiskTotalSize:"+infoBean.diskTotalSize);
    	System.out.println("TotalFreeSize:"+infoBean.diskTotalFreeSize);
    	
    	for(int i = 0; i < infoBean.avliaLogicDiskCount; i++){
    		LogicDiskInfo b = logicDiskInfos.get(i);
    		System.out.println(
    				b.Caption
    				+","+b.Description
    				+","+b.DeviceID
    				+","+b.DriveType
    				+","+b.FileSystem
    				+","+b.FreeSpace
    				+","+b.Size
    				+","+b.VolumeName
    		);
    	}*/
    	//getSystemHostName();
    	//getSystemMem();
    	//System.out.println("�������ڴ�="+getTotalPhysicMem() );
//		final BufferedReader strin = new BufferedReader(new InputStreamReader(
//				System.in));
//    	strin.readLine();
    	ProcessInfo readProcessNamePidsInfo = readProcessNamePidsInfo("feiq.exe", "-1") ;
    	System.out.println(readProcessNamePidsInfo);
    	
    }
}  
